import React from 'react'
import css from './back_page_top.module.less'
import topImg from './return-top.png'

type P = {
  // 显示隐藏
  show: boolean
  // 距离底部位置
  bottom: number
  // 自定义返回顶部操作
  toTopHandel: boolean
  // 自定义返回操作
  toTop?: () => void
}

type S = {
  thr: boolean
  showTopBtn: boolean
}

export default class BackPageTop extends React.Component<P, S> {
  static defaultProps = {
    show: true,
    bottom: 70,
    toTopHandel: false
  }
  constructor(props: P) {
    super(props)
    this.state = {
      thr: false,
      showTopBtn: false
    }
  }
  componentDidMount() {
    window.addEventListener('scroll', this.onScrollFn, false)
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.onScrollFn)
  }
  toTop = () => {
    if (this.props.toTopHandel) {
      if (this.props.toTop) {
        this.props.toTop()
      } else {
        console.info('没有自定义处理函数')
      }
      return
    }
    document.body.scrollIntoView({ behavior: 'smooth' })
  }
  onScrollFn = () => {
    if (this.state.thr) return
    this.setState({ thr: true })
    let scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop
    let screeHeight =
      document.documentElement.clientHeight || document.body.clientHeight // 屏幕高
    // 超过两屏显示返回顶部按钮
    if (scrollTop > screeHeight * 2) {
      this.setState({ showTopBtn: true })
    } else {
      this.setState({ showTopBtn: false })
    }
    // 节流100ms
    setTimeout(() => {
      this.setState({ thr: false })
    }, 100)
  }
  render() {
    return (
      <div
        className={css.back_page_top}
        style={
          this.props.show && this.state.showTopBtn
            ? { bottom: `calc(${this.props.bottom}vw/3.75` }
            : { display: 'none' }
        }
      >
        <img src={topImg} alt="err" onClick={this.toTop} />
      </div>
    )
  }
}
